package de.unistuttgart.iaas.interaction.skype;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;

import com.skype.Skype;
import com.skype.Friend;
import com.skype.*;
import de.unistuttgart.iaas.interaction.skype.database.MySQLAccess;
import de.unistuttgart.iaas.interaction.skype.util.ConfigFileHandler;

public class Register {

	public static void register(String configurationData)
    {

		ConfigFileHandler config = new ConfigFileHandler(configurationData);
		MySQLAccess dao = new MySQLAccess();

   	    try
   	    {
   			Connection conn = dao.connDataBase(config);
   	    	Friend[] friends = Skype.getContactList().getAllUserWaitingForAuthorization();
   	    	int friendNum = friends.length;
   	    	for(int i = 1; i<=friendNum;i++)
   	    	{
   	    		String skype_username = friends[i-1].getId();
   	    		
   	    		Statement statement = conn.createStatement();
   				ResultSet rs = statement.executeQuery("select skype_username from skydb."+config.getSkydb_table_register()+" where skype_username='"+ skype_username +"'");
   				if(!rs.next())
   				{
	   	    		String name = friends[i-1].getFullName();
	   	    		//.getDisplayName();
	   	    		
	   	   			PreparedStatement preStatementRegister= conn.prepareStatement("insert into skydb.register(skype_username,name) values(?,?)");
	   				preStatementRegister.setString(1,skype_username);
	   				preStatementRegister.setString(2,name);
	   				preStatementRegister.executeUpdate();
	   				preStatementRegister.close();
	   				
   					friends[i-1].setAuthorized(true);
	   	    		friends[i-1].setBlocked(false);
	   	    		SkypeGetRequest.skypeGetRequest("text", "Your register is successful!", skype_username, "no", "", "");
//	   				Chat chat = Skype.getContactList().getFriend(skype_username).chat();
//	   				chat.send("Your register is successful!");
   				}  	    		
   	    	}

    	}catch(Exception e)
   	    {
   	    	System.out.println("Error in register!");
   	    }
    }
}
